/*
 * EmployeePositionsEditor.java
 *
 * Created on November 19, 2006, 4:42 PM
 */

package org.foment.gem.beans;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import static org.foment.joliage3.core.internationalization.Internationalization.i18n;
import org.foment.joliage3.sql.Database;
import org.omg.CORBA.DATA_CONVERSION;
import org.foment.gem.Integrator;
import org.foment.data.User;

/**
 *
 * @author  jaksa
 */
public class EmployeePositionsEditor extends javax.swing.JPanel implements java.io.Serializable, User.UserListener {
    
    /** Creates new form BeanForm */
    public EmployeePositionsEditor() {
        initComponents();
        setComponents();

        Integrator._user.addListener(this);

        checkPrivileges();
    }


  public void userLoggedIn() {

      checkPrivileges();
  }

  /* see if user has all privileges or disable all elements */
  private void checkPrivileges() {

      // if user doesn't have all access disable all fields
      java.util.LinkedList<java.awt.Container> containers = new java.util.LinkedList();
      containers.add(this);

         while(!containers.isEmpty()) {

             java.awt.Container current = containers.getFirst(); // get first element from list
             containers.removeFirst();                           // now remove it from list, it is not needed anymore

             for (java.awt.Component component: current.getComponents()) {

                 if (!Integrator._user.getPrivAllAccess())
                     component.setEnabled(false);
                 else
                     component.setEnabled(true);
             }
                  
         }

         if (!Integrator._user.getPrivAllAccess()) {

            // now disable buttons
            btnNewPosition.setEnabled(false);
            btnNewPosition.setVisible(false);

            btnModifyPosition.setEnabled(false);
            btnModifyPosition.setVisible(false);

            btnDeletePosition.setEnabled(false);
            btnDeletePosition.setVisible(false);

         } else {

            // now enable buttons
            btnNewPosition.setEnabled(true);
            btnNewPosition.setVisible(true);

            btnModifyPosition.setEnabled(true);
            btnModifyPosition.setVisible(true);

            btnDeletePosition.setEnabled(true);
            btnDeletePosition.setVisible(true);
         }

  }

    
    private void setComponents()
    {
        comboJob.setQuery("SELECT JobID AS keyName, JobTitle AS fieldName FROM Job;");
        comboJob.listenTables("Job");
        
        comboJobType.setQuery("SELECT JobTypeID AS keyName, JobTypeTitle AS fieldName FROM JobType WHERE "+
              "JobID = " + comboJob.getValue() + ";");
        comboJobType.listenTables("JobType");
        listCurrentPositions.listenTables("JobType, EmployeeJobType");

    }
    private void clearGui()
    {
        txtExpirationDate.setText("");
        txtRemainingDays.setText("");
        jcbActualPosition.setSelected(false);
        jcbEmployeeInactive.setSelected(false);
        jcbPartTime.setSelected(false);
        dfPositionStartDate.setValue(null);
        dfReturnDate.setValue(null);

    }

    public void update() throws SQLException
    {
        clearGui();
        
        lblEmployee.setText(
        "<html>(" + Database.getTable("Employee").getResultSet().getString("EmployeeID") + ") " +
        "<b>" + Database.getTable("Employee").getResultSet().getString("EmployeeSurname") + ", " +
        Database.getTable("Employee").getResultSet().getString("EmployeeFirstName") + "</b>"
        );
        
        _currentEmployee = Database.getTable("Employee").getResultSet().getInt("EmployeeID");

        String query = "SELECT jt.JobTypeID AS keyName, jt.JobTypeTitle AS fieldName from JobType jt, " +
                "EmployeeJobType ejt WHERE ejt.EmployeeID = " + _currentEmployee + " AND ejt.JobTypeID = jt.JobTypeID;";

        /* keyName je redni broj reda u tabeli EmployeeJobType. On je dovoljan za potpunu identifikaciju
         * reda (jer je primarni kljuc)
          jt.JobTYpeID je ostavljen, onako, bez nekog razloga. */
        query = "SELECT ejt.EmployeeJobTypeID AS keyName, jt.JobTypeID, jt.JobTypeTitle AS fieldName FROM JobType jt, " +
                "EmployeeJobType ejt WHERE ejt.EmployeeID = " + _currentEmployee + " AND ejt.JobTypeID = jt.JobTypeID;";
        
        listCurrentPositions.setQuery(query);

        // dohvatamo podatke o detaljima zaposlenog
        query = "SELECT * from EmployeeJobDetails ejd WHERE EmployeeID = '" + _currentEmployee + "' ; ";
        try
        {
            Connection conn = Database.getConnection();
            ResultSet rs = conn.createStatement().executeQuery( query );

            if( rs.first() )
            {
                jcbEmployeeInactive.setSelected( rs.getInt("EmployeeJobDetailsInactive") == 1 );
                dfReturnDate.setValue( rs.getDate("EmployeeJobDetailsInactiveEndDate") );

                jcbPartTime.setSelected( rs.getInt ("EmployeeJobDetailsPartimeJob") == 1 );
                jtfPartTimePercent.setText( "" + rs.getInt( "EmployeeJobDetailsPartimeJobPercent" ) );
            }
            rs.close();
            conn.close();
        }
        catch( SQLException e)
        {
            e.printStackTrace();
        }
        // staviti OVO u setComponents()
        
        
        btnDeletePosition.setEnabled(false);
        btnModifyPosition.setEnabled(false);

    }
    
    private String formatDate(int value, String pattern)
    {
        java.text.DecimalFormat df = new java.text.DecimalFormat(pattern);
        return df.format((double) value);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlEmployee = new javax.swing.JPanel();
        lblEmployee = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listCurrentPositions = new org.foment.joliage3.newt.SQLListBox();
        lblJob = new javax.swing.JLabel();
        lblJobType = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        comboJob = new org.foment.joliage3.newt.SQLComboBox();
        comboJobType = new org.foment.joliage3.newt.SQLComboBox();
        btnModifyPosition = new javax.swing.JButton();
        btnNewPosition = new javax.swing.JButton();
        btnDeletePosition = new javax.swing.JButton();
        dfPositionStartDate = new org.foment.joliage3.newt.DateField();
        lblExpirationDate = new javax.swing.JLabel();
        txtExpirationDate = new javax.swing.JTextField();
        txtRemainingDays = new javax.swing.JTextField();
        lblRemainingDays = new javax.swing.JLabel();
        jcbActualPosition = new javax.swing.JCheckBox();
        pnlEmployeeJobDetails = new javax.swing.JPanel();
        jcbPartTime = new javax.swing.JCheckBox();
        jtfPartTimePercent = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jcbEmployeeInactive = new javax.swing.JCheckBox();
        dfReturnDate = new org.foment.joliage3.newt.DateField();
        jLabel3 = new javax.swing.JLabel();
        btnEmployeeJobDetailsConfirm = new javax.swing.JButton();

        lblEmployee.setFont(new java.awt.Font("Dialog", 0, 12));
        lblEmployee.setText(".");

        org.jdesktop.layout.GroupLayout pnlEmployeeLayout = new org.jdesktop.layout.GroupLayout(pnlEmployee);
        pnlEmployee.setLayout(pnlEmployeeLayout);
        pnlEmployeeLayout.setHorizontalGroup(
            pnlEmployeeLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployeeLayout.createSequentialGroup()
                .addContainerGap()
                .add(lblEmployee, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 913, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnlEmployeeLayout.setVerticalGroup(
            pnlEmployeeLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployeeLayout.createSequentialGroup()
                .addContainerGap()
                .add(lblEmployee)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        listCurrentPositions.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listCurrentPositionsValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listCurrentPositions);

        lblJob.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblJob.setText(i18n("Job"));

        lblJobType.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblJobType.setText(i18n("Position"));

        jLabel1.setText(i18n("Date"));

        comboJob.setFieldName("JobTitle");
        comboJob.setKeyName("JobID");
        comboJob.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboJobActionPerformed(evt);
            }
        });

        btnModifyPosition.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_update.png"))); // NOI18N
        btnModifyPosition.setText(i18n("Modify position"));
        btnModifyPosition.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModifyPositionActionPerformed(evt);
            }
        });

        btnNewPosition.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_insert.png"))); // NOI18N
        btnNewPosition.setText(i18n("Add new position"));
        btnNewPosition.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewPositionActionPerformed(evt);
            }
        });

        btnDeletePosition.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_reset.png"))); // NOI18N
        btnDeletePosition.setText(i18n("Remove position"));
        btnDeletePosition.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletePositionActionPerformed(evt);
            }
        });

        lblExpirationDate.setText(i18n("Expires"));

        txtExpirationDate.setEnabled(false);

        txtRemainingDays.setEnabled(false);

        lblRemainingDays.setText(i18n("Remaining days"));

        jcbActualPosition.setText("Aktuelna pozicija");

        pnlEmployeeJobDetails.setBorder(javax.swing.BorderFactory.createTitledBorder("Podaci o statusu zaposlenog"));

        jcbPartTime.setText("Nepuno radno vreme");
        jcbPartTime.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbPartTimeActionPerformed(evt);
            }
        });

        jLabel2.setText("%");

        jcbEmployeeInactive.setText("Status mirovanja");

        jLabel3.setText("Do:");

        btnEmployeeJobDetailsConfirm.setText("OK");
        btnEmployeeJobDetailsConfirm.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEmployeeJobDetailsConfirmActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout pnlEmployeeJobDetailsLayout = new org.jdesktop.layout.GroupLayout(pnlEmployeeJobDetails);
        pnlEmployeeJobDetails.setLayout(pnlEmployeeJobDetailsLayout);
        pnlEmployeeJobDetailsLayout.setHorizontalGroup(
            pnlEmployeeJobDetailsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployeeJobDetailsLayout.createSequentialGroup()
                .add(15, 15, 15)
                .add(pnlEmployeeJobDetailsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(pnlEmployeeJobDetailsLayout.createSequentialGroup()
                        .add(btnEmployeeJobDetailsConfirm)
                        .addContainerGap())
                    .add(pnlEmployeeJobDetailsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(pnlEmployeeJobDetailsLayout.createSequentialGroup()
                            .add(jcbPartTime)
                            .add(40, 40, 40)
                            .add(jtfPartTimePercent, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jLabel2)
                            .addContainerGap())
                        .add(pnlEmployeeJobDetailsLayout.createSequentialGroup()
                            .add(jcbEmployeeInactive)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 38, Short.MAX_VALUE)
                            .add(jLabel3)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(dfReturnDate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(35, 35, 35)))))
        );
        pnlEmployeeJobDetailsLayout.setVerticalGroup(
            pnlEmployeeJobDetailsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployeeJobDetailsLayout.createSequentialGroup()
                .add(15, 15, 15)
                .add(pnlEmployeeJobDetailsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jcbPartTime)
                    .add(jLabel2)
                    .add(jtfPartTimePercent, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(pnlEmployeeJobDetailsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(pnlEmployeeJobDetailsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jcbEmployeeInactive)
                        .add(jLabel3))
                    .add(dfReturnDate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnEmployeeJobDetailsConfirm)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployee, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 191, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(54, 54, 54)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(lblJobType)
                                .add(lblJob)
                                .add(jLabel1))
                            .add(lblExpirationDate)
                            .add(lblRemainingDays))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(txtRemainingDays, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)
                            .add(txtExpirationDate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)
                            .add(dfPositionStartDate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)
                            .add(comboJob, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)
                            .add(comboJobType, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)))
                    .add(layout.createSequentialGroup()
                        .add(318, 318, 318)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(pnlEmployeeJobDetails, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jcbActualPosition))
                        .add(119, 119, 119)))
                .add(181, 181, 181))
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(btnNewPosition, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 183, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnModifyPosition, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 190, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnDeletePosition, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 181, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(357, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(pnlEmployee, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(lblJob)
                            .add(comboJob, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(comboJobType, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(lblJobType))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(dfPositionStartDate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel1))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(txtExpirationDate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(lblExpirationDate))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(txtRemainingDays, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(lblRemainingDays))))
                .add(1, 1, 1)
                .add(jcbActualPosition)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(pnlEmployeeJobDetails, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(39, 39, 39)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnNewPosition)
                    .add(btnModifyPosition)
                    .add(btnDeletePosition))
                .addContainerGap(134, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void listCurrentPositionsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listCurrentPositionsValueChanged
        // TODO add your handling code here:
        btnDeletePosition.setEnabled(true);
        btnModifyPosition.setEnabled(true);
        
        listCurrentPositions.listener();
        int employeeJobTypeID = listCurrentPositions.getValue();
        
        if (_currentEmployee != -1 && employeeJobTypeID != -1)
        {
            // get selected position from the list
            java.sql.Date date = null;
            int jobID    = -1;
            int jobTypeID = -1; // Dodao 09.09.2010
            String active = "0";
            
            String query; /* = "SELECT emp.EmployeeJobTypeStartDate as startDate, " +
                    "jb.JobID, emp.EmployeeJobTypeActive as active FROM EmployeeJobType emp, " +
                    "JobType jb WHERE emp.EmployeeID = " + _currentEmployee + " AND emp.JobTypeID = " + employeeJobTypeID +
                     " AND jb.JobTypeID = " + employeeJobTypeID + ";"; */

            query = "SELECT jb.JobID as JobID, jb.JobTypeID as JobTypeID, ejt.EmployeeJobTypeStartDate as startDate, ejt.EmployeeJobTypeActive as active " +
                    " FROM EmployeeJobType ejt, JobType jb WHERE jb.JobTypeID = ejt.JobTypeID AND ejt.EmployeeJobTypeID = " + employeeJobTypeID + " ;";
            try
            {
                Connection conn = Database.getConnection();
                ResultSet rs = conn.createStatement().executeQuery(query);
                
                while (rs.next())
                {
                    jobID = rs.getInt("JobID");
                    jobTypeID = rs.getInt("JobTypeID");
                    date  = rs.getDate("startDate");
                    active = rs.getString("active");
                }
                rs.close();
                conn.close();

            } catch (SQLException ex)
            {
                ex.printStackTrace();
            }
            
            // set this position for combo boxes
            comboJob.setValue(jobID);
            comboJobType.setValue(jobTypeID);
            
            jcbActualPosition.setSelected(active.equals("1"));
            // set date 
            dfPositionStartDate.setValue(date);

            //System.out.println("JobID = " + jobID + " JobTypeID = " + jobTypeID + " position = " + employeeJobTypeID );

            /* --- displays date when this position will expire and number of days left until then
             *
             * upper query displays how many days are left until the end of this position duration
             *
             * racunamo preostale dane za tu poziciju tog zaposlenog. vazno je da sam izmenio
             * WHERE EmployeeJobTypeID = employeeJobTypeID, a ne kako je bilo WHERE EmployeeID = _currentEmployee
             */
            query = "SELECT (TO_DAYS(DATE(EmployeeJobTypeExpirationDate)) - TO_DAYS(DATE(NOW()))) AS remainingDaysNum, " +
                    "EmployeeJobTypeExpirationDate FROM EmployeeJobType WHERE EmployeeJobTypeID = "+ employeeJobTypeID +";";

            try {
                Connection  conn = Database.getConnection();
                ResultSet rs = conn.createStatement().executeQuery(query);

                while (rs.next()) {

                    String endDate = rs.getString("EmployeeJobTypeExpirationDate");
                    int daysNum    = rs.getInt("remainingDaysNum");

                    if (endDate != null)
                        txtExpirationDate.setText(endDate);

                    txtRemainingDays.setText("" + daysNum);
                }
                rs.close();
                conn.close();

            } catch (SQLException ex) {
                ex.printStackTrace();
            }


        }
        
    }//GEN-LAST:event_listCurrentPositionsValueChanged

    private void btnModifyPositionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModifyPositionActionPerformed
        // TODO add your handling code here:
        
        int employeeJobTypeID    = listCurrentPositions.getValue();
        int newPosition = comboJobType.getValue();
        boolean notSelected = listCurrentPositions.isSelectionEmpty();
        String active = jcbActualPosition.isSelected() ? "1" : "0";
        
        if (!notSelected && _currentEmployee != -1 && employeeJobTypeID != -1 && newPosition != -1)
        {
            // update job position first
            String message = i18n("Are you sure you want to modify position for this Employee?");
            String[] options = {i18n("Yes"), i18n("No")};

            int option = jOptionPane.showOptionDialog(this, message, "Foment Group", jOptionPane.YES_NO_OPTION, jOptionPane.QUESTION_MESSAGE, null, options, 0);
            
            if (option == JOptionPane.YES_OPTION)
            {
                int jobDuration = -1;

                try
                {
                    Connection conn = Database.getConnection();
                    String jobQuery = "SELECT JobTypeDuration FROM JobType WHERE JobTypeID = " + newPosition + " LIMIT 1;";
                    ResultSet rs = conn.createStatement().executeQuery(jobQuery);
                    
                    while (rs.next())
                        jobDuration = rs.getInt("JobTypeDuration");

                    rs.close();
                    conn.close();
                        
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                
                String positionStartDate = new java.text.SimpleDateFormat("yyyy-MM-dd").format(dfPositionStartDate.getValue());
                
                String positionEndDate = new String();
                if (jobDuration > 0)
                    positionEndDate = "DATE_ADD('" + positionStartDate + "', INTERVAL " + jobDuration + " YEAR)";
                else
                    positionEndDate = "NULL";

                String query; /* // Old query
                        = "UPDATE EmployeeJobType SET JobTypeID = " + newPosition + ", " +
                        "EmployeeJobTypeStartDate = '" + positionStartDate + "', " +
                        "EmployeeJobTypeExpirationDate = "+ positionEndDate + ", " +
                        "EmployeeJobTypeActive = '" + active + "'" +
                        " WHERE " +
                        "JobTypeID = "+ employeeJobTypeID +" AND EmployeeID = "+ _currentEmployee +";"; */

                query = "UPDATE EmployeeJobType SET JobTypeID = " + newPosition + ", " +
                        "EmployeeJobTypeStartDate = '" + positionStartDate + "', " +
                        "EmployeeJobTypeExpirationDate = "+ positionEndDate + ", " +
                        "EmployeeJobTypeActive = '" + active + "'" +
                        " WHERE " +
                        "EmployeeJobTypeID = " + employeeJobTypeID + " ; ";
                try
                {
                    Connection conn = Database.getConnection();
                    conn.createStatement().executeUpdate(query);
                    Database.getTable("EmployeeJobType").reload();
                    conn.close();
                } catch (SQLException ex) { ex.printStackTrace(); }
                
                listCurrentPositions.refresh();
            } 
        }
        
    }//GEN-LAST:event_btnModifyPositionActionPerformed

    private void btnDeletePositionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletePositionActionPerformed
        // TODO add your handling code here:
        boolean notSelected = listCurrentPositions.isSelectionEmpty();
        
        if (!notSelected && _currentEmployee != -1)
        {
            String message = i18n("Are you sure you want to delete position for this Employee?");
            String[] options = {i18n("Yes"), i18n("No")};

            int option = jOptionPane.showOptionDialog(this, message, "Foment Group", jOptionPane.YES_NO_OPTION, jOptionPane.QUESTION_MESSAGE, null, options, 0);
            
            if (option == jOptionPane.YES_OPTION)
            {
                String query = "DELETE FROM EmployeeJobType WHERE EmployeeJobTypeID = " + listCurrentPositions.getValue() + ";";

                try
                {
                    Connection  conn = Database.getConnection();
                    conn.createStatement().executeUpdate(query);
                    Database.getTable("EmployeeJobType").reload();
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                
                listCurrentPositions.refresh();
            }
        }
        
    }//GEN-LAST:event_btnDeletePositionActionPerformed

    private void btnNewPositionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewPositionActionPerformed
        // TODO add your handling code here:
        // display comfirmation dialog and check if date is entered correctly

        if (_currentEmployee != -1) {
            
            String message = i18n("Are you sure you want to add new position for this Employee?");
            String[] options = {i18n("Yes"), i18n("No")};
            String active = jcbActualPosition.isSelected() ? "1" : "0";
            
            int option = jOptionPane.showOptionDialog(this, message, "Foment Group", jOptionPane.YES_NO_OPTION, jOptionPane.QUESTION_MESSAGE, null, options, 0);
            
            if (option == JOptionPane.YES_OPTION)
            {
                // get date and form correct string for database
                int jobTypeID = comboJobType.getValue();
                String positionStartDate = new java.text.SimpleDateFormat("yyyy-MM-dd").format(dfPositionStartDate.getValue());
                int jobDuration = -1;

                try
                {
                    String jobQuery = "SELECT JobTypeDuration FROM JobType WHERE JobTypeID = " + jobTypeID + " LIMIT 1;";
                    Connection  conn = Database.getConnection();
                    ResultSet rs = conn.createStatement().executeQuery(jobQuery);
                    
                    while (rs.next())
                        jobDuration = rs.getInt("JobTypeDuration");
                   
                    rs.close();
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                
                String positionEndDate = new String();
                if (jobDuration > 0)
                    positionEndDate = "DATE_ADD('" + positionStartDate + "', INTERVAL " + jobDuration + " YEAR)";
                else
                    positionEndDate = "NULL";

                String query = "INSERT INTO EmployeeJobType (EmployeeID, JobTypeID, " +
                        "EmployeeJobTypeStartDate, EmployeeJobTypeExpirationDate, EmployeeJobTypeActive) " +
                        "VALUES (" + _currentEmployee + ", " + jobTypeID + ", " +
                        "'" + positionStartDate + "', " + positionEndDate + ", '" + active+ "');";

                try
                {
                    Connection  conn = Database.getConnection();
                    conn.createStatement().executeUpdate(query);
                    listCurrentPositions.setValue(jobTypeID);
                    Database.getTable("EmployeeJobType").reload();
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }

            }
        }
        
    }//GEN-LAST:event_btnNewPositionActionPerformed

    private void comboJobActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboJobActionPerformed
        // TODO add your handling code here:
            comboJobType.setQuery("SELECT JobTypeID AS keyName, JobTypeTitle AS fieldName FROM JobType WHERE "+
               "JobID = "+comboJob.getValue()+";");
    }//GEN-LAST:event_comboJobActionPerformed

    private void jcbPartTimeActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jcbPartTimeActionPerformed
    {//GEN-HEADEREND:event_jcbPartTimeActionPerformed
        // TODO add your handling code here:
        if( jcbPartTime.isSelected() )
        {
            jtfPartTimePercent.setEnabled(true);
        }
        else
        {
            jtfPartTimePercent.setText("");
            jtfPartTimePercent.setEnabled(false);
        }
    }//GEN-LAST:event_jcbPartTimeActionPerformed

    private void btnEmployeeJobDetailsConfirmActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnEmployeeJobDetailsConfirmActionPerformed
    {//GEN-HEADEREND:event_btnEmployeeJobDetailsConfirmActionPerformed
        // TODO add your handling code here:
        int partTimePercent = 0;
        String date = dfReturnDate.getValue() != null ? ("'" + dfReturnDate.getFormattedValue() + "'") : "NULL";
        //System.out.println( date );
       
        if( jcbPartTime.isSelected() )
        {
            try
            {
                partTimePercent = Integer.parseInt(jtfPartTimePercent.getText());
                if ( partTimePercent < 0 || partTimePercent > 100 )
                    throw new java.lang.NumberFormatException();
            }

            catch( java.lang.NumberFormatException e )
            {
                JOptionPane.showMessageDialog(pnlEmployeeJobDetails, "Nekorektan unos procenta", "Unos nepunog radnog vremena", JOptionPane.ERROR_MESSAGE);
            }
        }
        
        
        String query = "INSERT INTO EmployeeJobDetails "
                        + "( EmployeeID, EmployeeJobDetailsInactive, EmployeeJobDetailsInactiveEndDate, EmployeeJobDetailsPartimeJob ,EmployeeJobDetailsPartimeJobPercent )"
                        + " VALUES"
                        + "(" + _currentEmployee + ", "
                        + ( jcbEmployeeInactive.isSelected() ? " 1 " : " 0 "  ) + ", "
                        + ( jcbEmployeeInactive.isSelected() ?  date  : " NULL ") + ", "
                        + ( jcbPartTime.isSelected() ? " 1 " : " 0 " ) + ", "
                        + ( jcbPartTime.isSelected() ? partTimePercent : Integer.parseInt("0" ) )
                        + ")"
                        + "ON DUPLICATE KEY UPDATE "
                        + "EmployeeJobDetailsInactive = " + ( jcbEmployeeInactive.isSelected() ? " 1 " : " 0 " ) + ", "
                        + "EmployeeJobDetailsInactiveEndDate = " + ( jcbEmployeeInactive.isSelected() ? date  : " NULL ") + ", "
                        + "EmployeeJobDetailsPartimeJob = " + ( jcbPartTime.isSelected() ? " 1 " : " 0 ") + ", "
                        + "EmployeeJobDetailsPartimeJobPercent = " + ( jcbPartTime.isSelected() ? partTimePercent : Integer.parseInt("0" ) )
                        + " ;";
        
        //System.out.println( query );
        
        try
        {
            Connection  conn = Database.getConnection();
            conn.createStatement().executeUpdate(query);
            Database.getTable("EmployeeJobDetails").reload();
            conn.close();
        }
        catch( SQLException e )
        {
            e.printStackTrace();
        }
     
    }//GEN-LAST:event_btnEmployeeJobDetailsConfirmActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDeletePosition;
    private javax.swing.JButton btnEmployeeJobDetailsConfirm;
    private javax.swing.JButton btnModifyPosition;
    private javax.swing.JButton btnNewPosition;
    private org.foment.joliage3.newt.SQLComboBox comboJob;
    private org.foment.joliage3.newt.SQLComboBox comboJobType;
    private org.foment.joliage3.newt.DateField dfPositionStartDate;
    private org.foment.joliage3.newt.DateField dfReturnDate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JCheckBox jcbActualPosition;
    private javax.swing.JCheckBox jcbEmployeeInactive;
    private javax.swing.JCheckBox jcbPartTime;
    private javax.swing.JTextField jtfPartTimePercent;
    private javax.swing.JLabel lblEmployee;
    private javax.swing.JLabel lblExpirationDate;
    private javax.swing.JLabel lblJob;
    private javax.swing.JLabel lblJobType;
    private javax.swing.JLabel lblRemainingDays;
    private org.foment.joliage3.newt.SQLListBox listCurrentPositions;
    private javax.swing.JPanel pnlEmployee;
    private javax.swing.JPanel pnlEmployeeJobDetails;
    private javax.swing.JTextField txtExpirationDate;
    private javax.swing.JTextField txtRemainingDays;
    // End of variables declaration//GEN-END:variables
 
    private int _currentEmployee  = -1;
    private JOptionPane jOptionPane;
    
}
